﻿namespace EyeOpen.Security.Mvc.Controllers
{
	using System;
	using System.Web.Mvc;
	using System.Web.Security;

	using EyeOpen.Security.Data;
	using EyeOpen.Security.Mvc.Models;
	using EyeOpen.Security.Service;
	using EyeOpen.Web.Mvc;

	public class SecurityController : BaseController
	{
		private readonly ISecurityUnitOfWork uow;

		public SecurityController(ISecurityUnitOfWork uow)
		{
			this.uow = uow;
		}

		[HttpGet]
		public ActionResult Login()
		{
			return Render("Login");
		}

		[HttpPost]
		public ActionResult Authenticate(UserLoginViewModel userLoginViewModel)
		{
			if (!ModelState.IsValid)
			{
				return Render("Login");
			}

			using (uow)
			{
				var isValidUser =
					new UserLoginService()
						.IsValidUser(userLoginViewModel.Email, userLoginViewModel.Password, uow);

				if (!isValidUser)
				{
					ModelState.AddModelError(string.Empty, "Email or password are not valid");

					return
						Render("Login");
				}
			}

			FormsAuthentication
				.SetAuthCookie(userLoginViewModel.Email, false);

			return
				RedirectToAction("Create");
		}

		[HttpGet]
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();

			return
				RedirectToAction("Index", "FrontEnd");
		}

		[HttpGet]
		public ActionResult Create()
		{
			return
				Render("Create");
		}

		[HttpPost]
		public ActionResult Save(CreateUserViewModel createUserViewModel)
		{
			throw new NotImplementedException();
			////using (uow)
			////{
			////    uow.UserRepository.Add();
			////}
		}
	}
}